<!DOCTYPE html>
<html lang="zh_CN">

<head>
    <title>JSON在线编辑格式化</title>
    <meta charset="UTF-8" />
    <link rel="shortcut icon" href="assets/img/logo.png" type="image/x-icon">
    <style type="text/css" media="screen">
        .full-screen {
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
        }
        
        #editor {
            width: 100%;
            height: 100%;
        }
    </style>
</head>

<body>

    <div class="full-screen">
        <div class="half-width right-div" id="editor">
        </div>
    </div>

    <script type="text/javascript" src="assets/ace/ace.js"></script>
    <script type="text/javascript" src="assets/ace/mode-json.js"></script>
    <script type="text/javascript" src="assets/ace/theme-textmate.js"></script>
    <script type="text/javascript" src="assets/ace/worker-json.js"></script>
    <script>
        var editor = ace.edit("editor");
        editor.setTheme("ace/theme/textmate");
        var JavaScriptMode = ace.require("ace/mode/json").Mode;
        editor.session.setMode(new JavaScriptMode());
        editor.setValue('')


        editor.commands.addCommand({
            name: 'formatter',
            bindKey: {
                win: 'Ctrl-Alt-L',
                mac: 'Command-Alt-L'
            },
            exec: function(editor) {
                console.log("格式化json")
                var jsonText = editor.getValue()
                formatJson(jsonText)
            }
        })

        function formatJson(jsonText) {
            if (!jsonText) {
                return
            }
            try {
                var jsonObj = JSON.parse(jsonText)
                var jsonContent = JSON.stringify(jsonObj, null, 2)
                editor.setValue(jsonContent)
            } catch (e) {
                alert('json格式错误：' + e)
            }
        }
    </script>
</body>

</html>